package com.qfedu.openplateform.gateway.filter;

import com.qfedu.openplateform.common.entity.LoggerBean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * 日志拦截器
 *   记录所有的日志
 */
public class LogFilter  implements HandlerInterceptor {

    // 就是为每一个请求的线程 创建一个副本 变量,其他线程看不到
    ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override  // 请求之前 进行拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 记录请求路径 请求参数  请求的ip   ，响应  时长
        threadLocal.set(new Date());

        // 放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override// 整个请求响应 完成后
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        // 得到这个请求的时间差
        // 记录请求路径 请求参数  请求的ip   ，响应  时长
        //把我们要的数据找到,然后通过日志发送出去
        LoggerBean loggerBean = new LoggerBean();


        Date responeDate = new Date();
        loggerBean.setResponseTime(responeDate);//设置响应时间
        loggerBean.setApp_key(request.getParameter("app_key"));
        loggerBean.setApiName(request.getParameter("method"));
        loggerBean.setRemoteIp(request.getRemoteAddr());
        Date startTine = threadLocal.get();
        loggerBean.setReveivceTime(startTine);
        loggerBean.setTotalTime(responeDate.getTime() - startTine.getTime());//设置总时间
        try {
            loggerBean.setServerIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        loggerBean.setContent(request.getQueryString());

        System.out.println("loggerBean:"+loggerBean);

    }
}
